import { Component, OnInit } from '@angular/core';
import { ModalHelper, _HttpClient, MenuService } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { MenusReloadService } from 'src/app/shared/custom_services/MenusReload.service';

import { SysMenuEditComponent } from './edit/edit.component';

export interface TreeNodeInterface {
  ID: number;
  pid: number;
  name: string;
  type?: number;
  icon?: string;
  link?: string;
  sort?: number;
  children?: TreeNodeInterface[];
  parent?: TreeNodeInterface;
  expand?: boolean;
  level?: number;
}

@Component({
  selector: 'app-sys-menu',
  templateUrl: './menu.component.html'
})
export class SysMenuComponent implements OnInit {
  listOfMapData: TreeNodeInterface[] = [];
  mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.ID === d.ID)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: TreeNodeInterface): TreeNodeInterface[] {
    const stack: TreeNodeInterface[] = [];
    const array: TreeNodeInterface[] = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: true });

    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level! + 1, expand: false, parent: node });
        }
      }
    }

    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: { [key: string]: boolean }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.ID]) {
      hashMap[node.ID] = true;
      array.push(node);
    }
  }

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private msgSrv: NzMessageService,
    private menuService: MenuService,
    private menusReload: MenusReloadService
  ) {}

  ngOnInit(): void {
    this.loadMenuTree();
  }

  loadMenuTree(): void {
    this.http.get('api/menus').subscribe(res => {
      this.listOfMapData = res.data;
      this.listOfMapData.forEach(item => {
        this.mapOfExpandedData[item.ID] = this.convertTreeToList(item);
      });
    });
  }

  add(pid?: number): void {
    this.modal.createStatic(SysMenuEditComponent, { i: { id: 0, pid: pid || 0 } }).subscribe(() => {
      this.msgSrv.success('创建成功！');
      this.loadMenuTree();
      this.menusReload.reloadAntMenu();
    });
  }

  edit(record: any): void {
    this.modal.createStatic(SysMenuEditComponent, { i: { id: record.ID }, record: record }).subscribe(() => {
      this.msgSrv.success('更新成功！');
      this.loadMenuTree();
      this.menusReload.reloadAntMenu();
    });
  }

  delConfirm(record: any): void {
    if (record.children && record.children.length > 0) {
      this.msgSrv.warning('请先删除子级!');
      return;
    }
    this.http.delete(`api/menu/${record.ID}`).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.success(res.msg);
        return;
      }
      this.msgSrv.success('菜单删除成功');
      this.loadMenuTree();
      this.menusReload.reloadAntMenu();
    });
  }
}
